from flask import Blueprint, request, jsonify
from models import db, Project

project_bp = Blueprint('project', __name__)

@project_bp.route('/api/employees/<int:employee_id>/projects', methods=['GET'])
def get_projects(employee_id):
    projects = Project.query.filter_by(employee_id=employee_id).order_by(Project.start_date.desc()).all()
    return jsonify([project.to_dict() for project in projects])

@project_bp.route('/api/employees/<int:employee_id>/projects', methods=['POST'])
def create_project(employee_id):
    data = request.get_json()
    data['employee_id'] = employee_id
    project = Project(**data)
    db.session.add(project)
    db.session.commit()
    return jsonify({'message': '创建成功', 'id': project.id}), 201

@project_bp.route('/api/employees/<int:employee_id>/projects/<int:id>', methods=['PUT'])
def update_project(employee_id, id):
    project = Project.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    data = request.get_json()
    for key, value in data.items():
        setattr(project, key, value)
    db.session.commit()
    return jsonify({'message': '修改成功'})

@project_bp.route('/api/employees/<int:employee_id>/projects/<int:id>', methods=['DELETE'])
def delete_project(employee_id, id):
    project = Project.query.filter_by(id=id, employee_id=employee_id).first_or_404()
    db.session.delete(project)
    db.session.commit()
    return jsonify({'message': '删除成功'}) 